package cmd

import (
	"fmt"
	"os"
	"text/tabwriter"

	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
	"pets.ser163.cn/routers"
)

var routesCmd = &cobra.Command{
	Use:   "route:list",
	Short: "Print routes info",
	Run: func(cmd *cobra.Command, args []string) {
		r := gin.New()
		routers.InitAPIRoutes(r)
		printRoutes(r)
	},
}

func init() {
	rootCmd.AddCommand(routesCmd)
}

func printRoutes(r *gin.Engine) {
	w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', tabwriter.StripEscape)
	defer w.Flush()

	// 添加表头
	fmt.Fprintf(w, "METHOD\tPATH\tHANDLER\n")
	fmt.Fprintf(w, "------\t----\t-------\n")

	// 输出路由信息
	for _, route := range r.Routes() {
		fmt.Fprintf(w, "%s\t%s\t%s\n", route.Method, route.Path, route.Handler)
	}
}
